<template>
<div class="update-photo">
  <img :src="img" class="img" ref="img">
  <div class="toolbar">
    <div class="cancel" @click="$emit('close')">取消</div>
    <div class="confirm" @click="onConfirm">完成</div>
  </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { ref } from 'vue'
import { updateUserPhoto } from '@/api/user'
import { Toast } from 'vant'

export default {
  name: 'UpdatePhoto',
  mounted () { // 操作dom写mounted内
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  setup (props, context) {
    const cropper = ref(null)
    function onConfirm () {
      cropper.value.getCroppedCanvas().toBlob((blob) => { // 获取裁切后的图片对象
        updatePhoto(blob)
      })
    }
    async function updatePhoto (blob) {
      Toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁用背景点击
        duration: 0// 持续展示，直到下个Toast出现
      })
      try {
        // updateUserPhoto({
      //   photo: blob
      // }) 是错的哦，接口Content-Type是multipart/form-data的时候必须传FormData对象
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        context.emit('close')
        context.emit('updata-photo', data.data.photo)
        Toast.success('更新成功')
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast.fail('请重新登录')
        } else {
          Toast.fail('操作失败')
        }
      }
    }
    return {
      cropper,
      onConfirm
    }
  }
}
</script>

<style lang='less' scoped>
.update-photo{
  background: #000;
  height: 100%;
.img{
  display: block;
  max-width: 100%;
}
.toolbar{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;// 左右分开排布
  .cancel, .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
}

</style>
